package com.kede.api.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.kede.api.order.controller.po.CreatePackageOrderPo;
import com.kede.api.order.controller.po.RefusePackageOrderPo;
import com.kede.api.order.controller.po.SurePackageOrderPo;
import com.kede.api.order.service.IPackageManageService;
import com.kede.api.order.utils.OrderUtil;
import com.kede.dictenum.BoolDictEnum;
import com.kede.domain.PackageDomain;
import com.kede.domain.PackageOrderDomain;
import com.kede.domain.ZhiOrderGoodsListDomain;
import com.kede.domain.ZhiUserCertifiedDomain;
import com.kede.ienum.order.CertiTypeEnum;
import com.kede.pojo.PackageOrderStatus;
import com.kede.pojo.PackageStatusEnum;
import com.kede.pojo.PagePO;
import com.kede.pojo.ResHttp;
import com.kede.service.PackageOrderService;
import com.kede.service.PackageService;
import com.kede.service.ZhiOrderGoodsListService;
import com.kede.service.ZhiUserCertifiedService;
import com.kede.utils.CollectionUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author:Pr.li
 * @Date: create in 2023/9/17 14:55
 */
@Service
public class PackageManageServiceImpl implements IPackageManageService {

    public static final String PackageOrderNoKey = "PKG";

    @Resource
    private PackageOrderService packageOrderService;

    @Resource
    private PackageService packageService;

    @Resource
    private ZhiOrderGoodsListService zhiOrderGoodsListService;

    @Resource
    private ZhiUserCertifiedService zhiUserCertifiedService;

    @Override
    public ResHttp createPackageOrder(CreatePackageOrderPo packageOrderPo) {
        PackageOrderDomain packageOrderDomain = new PackageOrderDomain();
        packageOrderDomain.setReserveStartTime(packageOrderPo.getStartTime());
        packageOrderDomain.setReserveEndTime(packageOrderPo.getEndTime());
        packageOrderDomain.setCreateTime(LocalDateTime.now());
        packageOrderDomain.setDestCerId(packageOrderPo.getDescCerId());
        packageOrderDomain.setSrcCerId(packageOrderPo.getSrcCerId());
        packageOrderDomain.setSrcCerType(packageOrderPo.getSrcCerType().getCode());
        String randomNo = OrderUtil.getRandomNo(PackageOrderNoKey);
        packageOrderDomain.setNo(randomNo);
        packageOrderDomain.setStatus(PackageOrderStatus.WAITING.getStatus());
        List<PackageDomain> packageList = packageOrderPo.getPackageList();
        StringBuilder packageIdsBuilder = new StringBuilder();
        for (int i = 0,len = packageList.size(); i < len; i++) {
            PackageDomain packageDomain = packageList.get(i);
            setPackageCreateAfterStatus(packageOrderPo.getSrcCerType(),packageDomain);
            packageService.updateById(packageDomain);
            packageIdsBuilder.append(packageDomain.getId());
            if(i < len - 1){
                packageIdsBuilder.append(",");
            }
        }
        packageOrderDomain.setPackageIds(packageIdsBuilder.toString());
        boolean save = packageOrderService.save(packageOrderDomain);
        if (save){
            return ResHttp.ok();
        }
        return ResHttp.fail();
    }

    private void setPackageCreateAfterStatus(CertiTypeEnum certiType,PackageDomain packageDomain){
        switch (certiType){
            case STORE:
                packageDomain.setStatus(PackageStatusEnum.WaitQu.getStatus());
                break;
            case QUDAI:
                packageDomain.setStatus(PackageStatusEnum.WaitShi.getStatus());
                break;
        }
    }

    @Override
    public ResHttp getPackageOrderList(PagePO pagePO, Integer cerId,Integer isSrc,PackageOrderStatus status) {
        List<OrderItem> orders = pagePO.orders();
        if (CollectionUtil.Blank(orders)){
            orders.add(OrderItem.desc("create_time"));
        }
        LambdaQueryWrapper<PackageOrderDomain> queryWrapper = new LambdaQueryWrapper<>();
        boolean boolSrc = false;
        if (isSrc.equals(BoolDictEnum.TRUE.getCode())){
            boolSrc = true;
            queryWrapper.eq(PackageOrderDomain::getSrcCerId,cerId);
        }else {
            queryWrapper.eq(PackageOrderDomain::getDestCerId,cerId);
        }
        if (status != null){
            queryWrapper.eq(PackageOrderDomain::getStatus,status.getStatus());
        }
        PagePO<PackageOrderDomain> page = packageOrderService.page(pagePO, queryWrapper);
        List<PackageOrderDomain> records = page.getRecords();
        for (PackageOrderDomain record : records) {
            if (boolSrc){
                record.setDestInfo(zhiUserCertifiedService.getById(record.getDestCerId()));
            }else{
                record.setSrcInfo(zhiUserCertifiedService.getById(record.getSrcCerId()));
            }
        }
        return ResHttp.okData(page);
    }

    @Override
    public ResHttp getPackageOrderDetail(Integer id) {
        PackageOrderDomain order = packageOrderService.getById(id);
        String[] split = order.getPackageIds().split(",");
        ZhiUserCertifiedDomain srcInfo = zhiUserCertifiedService.getById(order.getSrcCerId());
        if (srcInfo!=null){
            order.setSrcInfo(srcInfo);
        }
        ZhiUserCertifiedDomain destInfo = zhiUserCertifiedService.getById(order.getDestCerId());
        if (destInfo!=null){
            order.setDestInfo(destInfo);
        }
        List<PackageDomain> detail  = new ArrayList<>();
        for (String packid : split) {
            PackageDomain packageDomain = packageService.getById(packid);
            String[] goods = packageDomain.getGoodIds().split(",");
            List<ZhiOrderGoodsListDomain> goodsListDomains = new ArrayList<>();
            for (String goodid : goods) {
                ZhiOrderGoodsListDomain good = zhiOrderGoodsListService.getById(goodid);
                goodsListDomains.add(good);
            }
            packageDomain.setGoodsList(goodsListDomains);
            detail.add(packageDomain);
        }
        order.setDetail(detail);
        return ResHttp.okData(order);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResHttp surePackageOrder(SurePackageOrderPo surePackageOrderPo) {
        PackageOrderDomain packageOrder = packageOrderService.getById(surePackageOrderPo.getOrderId());
        if (!packageOrder.getDestCerId().equals(surePackageOrderPo.getDestId())){
            return ResHttp.failMsg("当前签收操作无效");
        }
        String[] split = packageOrder.getPackageIds().split(",");
        Integer srcCerType = packageOrder.getSrcCerType();
        CertiTypeEnum parse = CertiTypeEnum.parse(srcCerType);
        List<PackageDomain> upList = new ArrayList<>();
        ZhiUserCertifiedDomain destCerInfo = zhiUserCertifiedService.getById(surePackageOrderPo.getDestId());
        BigDecimal totalRMB = new BigDecimal("0");
        switch (parse){
            case STORE:
                for (String pckid : split) {
                    PackageDomain pck = packageService.getById(pckid);
                    //这个包是处理过的 签收要跳过
                    if(!pck.getStatus().equals(PackageStatusEnum.WaitQu.getStatus())){
                        continue;
                    }
                    pck.setStatus(PackageStatusEnum.QuNormal.getStatus());
                    pck.setQuId(surePackageOrderPo.getDestId());
                    pck.setQuName(destCerInfo.getStoreName());
                    upList.add(pck);
                    //给区代加验收款
                    String[] goodIds = pck.getGoodIds().split(",");
                    List<ZhiOrderGoodsListDomain> batchList = new ArrayList<>();
                    for (String goodId : goodIds){
                        ZhiOrderGoodsListDomain good = zhiOrderGoodsListService.getById(goodId);
                        good.setQuId(surePackageOrderPo.getDestId());
                        batchList.add(good);
                        totalRMB = totalRMB.add(good.getDefaultQuMoney());
                    }
                    zhiOrderGoodsListService.updateBatchById(batchList);
                }
                break;
            case QUDAI:
                for (String pckid : split) {
                    PackageDomain pck = packageService.getById(pckid);
                    //这个包是处理过的 签收要跳过
                    if(!pck.getStatus().equals(PackageStatusEnum.WaitShi.getStatus())){
                        continue;
                    }
                    pck.setStatus(PackageStatusEnum.ShiNormal.getStatus());
                    pck.setShiId(surePackageOrderPo.getDestId());
                    pck.setShiName(destCerInfo.getStoreName());
                    upList.add(pck);
                    //给市代加验收款
                    String[] goodIds = pck.getGoodIds().split(",");
                    List<ZhiOrderGoodsListDomain> batchList = new ArrayList<>();
                    for (String goodId : goodIds){
                        ZhiOrderGoodsListDomain good = zhiOrderGoodsListService.getById(goodId);
                        good.setShiId(surePackageOrderPo.getDestId());
                        batchList.add(good);
                        totalRMB = totalRMB.add(good.getDefaultShiMoney());
                    }
                    zhiOrderGoodsListService.updateBatchById(batchList);
                }
                break;
            case SHIDAI:
                break;
        }
        //设置验收款
        destCerInfo.setValidMoney(destCerInfo.getValidMoney().add(totalRMB));
        zhiUserCertifiedService.updateById(destCerInfo);

        packageService.updateBatchById(upList);
        packageOrder.setStatus(PackageOrderStatus.SURE.getStatus());
        packageOrderService.updateById(packageOrder);
        return ResHttp.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResHttp refusePackageOrder(RefusePackageOrderPo refusePackageOrderPo) {
        PackageOrderDomain packageOrder = packageOrderService.getById(refusePackageOrderPo.getOrderId());
        if (!packageOrder.getDestCerId().equals(refusePackageOrderPo.getDestId())){
            return ResHttp.failMsg("当前签收操作无效");
        }
        String[] split = packageOrder.getPackageIds().split(",");
        boolean hasSetOrder = true;
        for (String pckid : split) {
            if (pckid.equals(refusePackageOrderPo.getPackageId().toString())){
                continue;
            }
            PackageDomain packageDomain = packageService.getById(pckid);
            //看有没有待处理的包裹，如果没有就需要设置订单状态了
            if (packageDomain.getStatus().equals(PackageStatusEnum.WaitQu.getStatus())
            || packageDomain.getStatus().equals(PackageStatusEnum.WaitShi.getStatus())){
                hasSetOrder = false;
            }
        }
        PackageDomain byId = packageService.getById(refusePackageOrderPo.getPackageId());
        byId.setReason(refusePackageOrderPo.getReason());
        Integer srcCerType = packageOrder.getSrcCerType();
        CertiTypeEnum parse = CertiTypeEnum.parse(srcCerType);
        switch (parse){
            case STORE:
                byId.setStatus(PackageStatusEnum.QuRefuse.getStatus());
                break;
            case QUDAI:
                byId.setStatus(PackageStatusEnum.ShiRefuse.getStatus());
                break;
        }
        packageService.updateById(byId);
        if (hasSetOrder){
            packageOrder.setStatus(PackageOrderStatus.SURE.getStatus());
            packageOrderService.updateById(packageOrder);
        }
        return ResHttp.okData(packageOrder);
    }

    @Override
    public ResHttp delOrder(Integer id) {
        PackageOrderDomain byId = packageOrderService.getById(id);
        if (byId!=null){
            packageOrderService.removeById(byId);
        }
        return ResHttp.ok();
    }

}
